<template>
  <div class="my-project-layout px_8">
    <div class="my_add flex justify_between align_center vertical_middle cursor_point pr_12"
      @click="handleModalAddAction">
      <img src="https://fengnull.gitee.io/picture_house/page/dataSource.jpg" class="h_100 my_add_img" alt="">
      <div class="my_add_text pl_8 fontsize_14">创建数据源</div>
    </div>
    <div class="my_header font_bolder px_4 pt_4 pb_4 sticky flex justify_between align_center">
      <div class="my_header_title">
        数据源列表
      </div>
      <div>
        <el-input size="small" placeholder="搜索" v-model.trim="query.name" @keyup.enter.native="getMySourceList"
          clearable @change="getMySourceList"></el-input>
      </div>
    </div>
    <el-table :data="sourceList" border stripe class="w_100 mt_20" v-loading="sourceLoading">
      <el-table-column type="index" width="50" label="序号" align="center" />
      <el-table-column property="name" align="center" label="数据源" width="180" />
      <el-table-column property="db_type" align="center" label="类型" width="180">
        <template #default="scope">
          <el-tag effect="dark" size="small" :type="showDbType(scope.row.db_type)">{{ scope.row.db_type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" property="host" label="主机" />
      <el-table-column align="center" property="remark" label="备注" />
      <el-table-column align="center" property="create_timestamp" label="创建时间">
        <template #default="scope">
          <span>{{ formatTime(scope.row.create_timestamp) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="small" type="success" class="cursor_point" @click="handleModalEditAction(scope.row)">更新
          </el-button>
          <el-button size="small" type="danger" class="cursor_point" @click="handleModalDelAction(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="mt_16 right" v-model:currentPage="query.size" :page-size="query.limit"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange"></el-pagination>
    <el-dialog v-model="SourceOpModel" :title="modalTitle[modalStatus]" width="45%" destroy-on-close>
      <el-form :model="sourceForm" :rules="rules" ref="sourceFormRef" label-placement="left" :label-width="100"
        size="small">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据源名称:" prop="name">
              <el-input placeholder="请输入数据源名称" v-model.trim="sourceForm.name" @change="handleFormChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据源类型:" prop="db_type" class="w_100">
              <el-select placeholder="请选择数据源类型" v-model="sourceForm.db_type" @change="handleFormChange">
                <el-option v-for="item in sqlTypeList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务器地址:" prop="host">
              <el-input placeholder="请输入服务器地址" v-model.trim="sourceForm.host" @change="handleFormChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务器端口号:" prop="port">
              <el-input-number class="input_number_100" placeholder="请输入服务器端口号" v-model="sourceForm.port"
                @change="handleFormChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名:" prop="user">
              <el-input placeholder="请输入用户名" v-model.trim="sourceForm.user" @change="handleFormChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码:" prop="password">
              <el-input placeholder="请输入密码" v-model.trim="sourceForm.password" show-password
                @change="handleFormChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库名称:" prop="db_name">
              <el-input placeholder="请输入数据源名称" v-model.trim="sourceForm.db_name" @change="handleFormChange" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="footer-modal text_right right_0">
        <el-button @click="handleCloseModal" plain size="small" class="cursor_point footer-modal--btn">取消</el-button>
        <el-button type="primary" size="small" class="footer-modal--btn base-primary-btn" @click="handleTestSource">测试
        </el-button>
        <el-button type="primary" size="small" class="footer-modal--btn cursor_point base-primary-btn m_lr_10"
          v-if="modalStatus === 'add'" v-loading="formLoading" :disabled="!submitFlag" @click="handleAddSource">确认
        </el-button>
        <el-button type="primary" size="small" class="footer-modal--btn cursor_point base-primary-btn m_lr_10"
          v-if="modalStatus === 'edit'" v-loading="formLoading" :disabled="!submitFlag" @click="handleEditSource">更新
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref } from "vue";
import {
  addDataSource,
  delDataSource,
  editDataSource,
  getDataSourceList,
  testDataSource,
} from "../../service/source";
import { sqlTypeList } from "../../utils/dict";
import { formatDate } from "../../utils/utils";

export default defineComponent({
  name: "my-source",
  setup() {
    const sourceLoading = ref(false);
    const formLoading = ref(false);
    const sourceList = ref([]);
    const SourceOpModel = ref(false);
    const modalStatus = ref("add");
    const total = ref(0);
    const modalTitle = ref({
      add: "新增数据源",
      edit: "编辑数据源",
    });
    const query = ref({
      name: "",
      size: 1,
      limit: 10,
    });
    const formatTime = (num) => {
      return formatDate(num, "yyyy-MM-dd hh:mm:ss");
    };
    const handleSizeChange = (pageSize) => {
      query.value.size = 1;
      query.value.limit = pageSize;
      getMySourceList();
    };
    const handleCurrentChange = (size) => {
      query.value.size = size;
      getMySourceList();
    };
    const sourceForm = ref({
      name: undefined,
      db_type: undefined,
      host: undefined,
      port: 0,
      user: undefined,
      password: undefined,
      db_name: undefined,
    });
    const sourceFormRef = ref(null);
    const submitFlag = ref(false);
    const handleFormChange = () => {
      submitFlag.value = false;
    };
    const resetForm = () => {
      sourceForm.value = {
        name: undefined,
        db_type: undefined,
        host: undefined,
        port: 0,
        user: undefined,
        password: undefined,
        db_name: undefined,
      };
    };
    const handleModalAddAction = () => {
      resetForm();
      modalStatus.value = "add";
      SourceOpModel.value = true;
    };
    const handleCloseModal = () => {
      SourceOpModel.value = false;
    };
    const getMySourceList = () => {
      sourceLoading.value = true;
      getDataSourceList(query.value).then((res) => {
        sourceList.value = res.data.result;
        sourceLoading.value = false;
        total.value = res.data.total;
      });
    };
    const handleTestSource = () => {
      formLoading.value = true;
      sourceFormRef.value.validate((valid) => {
        if (valid) {
          testDataSource(sourceForm.value)
            .then((res) => {
              formLoading.value = false;
              ElMessage({
                type: "success",
                message: "连接数据源成功",
              });
              submitFlag.value = true;
            })
            .catch(() => {
              ElMessage.error("连接数据源失败");
              formLoading.value = false;
            });
        }
      });
    };
    const handleAddSource = () => {
      formLoading.value = true;
      sourceFormRef.value.validate((valid) => {
        if (valid) {
          addDataSource(sourceForm.value)
            .then(() => {
              formLoading.value = false;
              ElMessage({
                type: "success",
                message: "新增数据源成功",
              });
              handleCloseModal();
              getMySourceList();
            })
            .catch(() => {
              ElMessage.error("新增数据源失败");
              formLoading.value = false;
            });
        }
      });
    };
    const handleModalEditAction = (rowData) => {
      resetForm();
      sourceForm.value = rowData;
      modalStatus.value = "edit";
      submitFlag.value = false;
      SourceOpModel.value = true;
    };
    const handleEditSource = () => {
      formLoading.value = true;
      sourceFormRef.value.validate((valid) => {
        if (valid) {
          editDataSource(sourceForm.value)
            .then(() => {
              formLoading.value = false;
              ElMessage({
                type: "success",
                message: "编辑数据源成功",
              });
              handleCloseModal();
              getMySourceList();
            })
            .catch(() => {
              ElMessage.error("编辑数据源失败");
              formLoading.value = false;
            });
        }
      });
    };
    const handleModalDelAction = (rowData) => {
      ElMessageBox.confirm(`你确定删除 ${rowData.name} 么？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "modal-confirm_btn",
        type: "warning",
      }).then(() => {
        handleDelSource(rowData);
      });
    };
    const showDbType = (type) => {
      let tagType;
      switch (type) {
        case "csv":
          tagType = "success";
          break;
        case "MySQL":
          tagType = "warning";
          break;
        case "Oracle":
          tagType = "error";
          break;
        case "PostgreSQL":
          tagType = "info";
          break;
        default:
          break;
      }
      return tagType;
    };
    const handleDelSource = (rowData) => {
      delDataSource({ data_source_id: rowData.data_source_id })
        .then(() => {
          ElMessage({
            type: "success",
            message: "删除数据源成功",
          });
          getMySourceList();
        })
        .catch(() => {
          sourceLoading.value = false;
        });
    };
    onMounted(() => {
      getMySourceList();
    });
    return {
      rules: {
        name: {
          required: true,
          trigger: ["blur", "input"],
          message: "请输入数据源名称",
        },
        db_type: {
          required: true,
          message: "请选择数据源类型",
          trigger: ["change"],
        },
        host: {
          required: true,
          message: "请输入服务器地址",
          trigger: ["input", "blur"],
        },
        user: {
          required: true,
          message: "请输入用户名",
          trigger: ["input", "blur"],
        },
        password: {
          required: true,
          message: "请输入密码",
          trigger: ["input", "blur"],
        },
        db_name: {
          required: true,
          message: "请输入数据库名称",
          trigger: ["input", "blur"],
        },
      },
      query,
      sourceList,
      SourceOpModel,
      sourceForm,
      submitFlag,
      sourceFormRef,
      modalStatus,
      modalTitle,
      sourceLoading,
      formLoading,
      total,
      formatTime,
      handleTestSource,
      handleAddSource,
      handleEditSource,
      sqlTypeList: sqlTypeList,
      handleSizeChange,
      handleCurrentChange,
      getMySourceList,
      handleCloseModal,
      handleModalAddAction,
      handleModalDelAction,
      handleModalEditAction,
      handleFormChange,
      resetForm,
      handleDelSource,
      showDbType,
    };
  },
});
</script>

<style lang="less" scoped></style>
